package com.terios.logic.ui;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.terios.R;
import com.terios.Status;
import com.terios.conts.CommonStrs;
import com.terios.intfs.IWeiboActivity;
import com.terios.intfs.PullToRefresh;
import com.terios.intfs.PullToRefresh.UpdateHandle;
import com.terios.logic.MainService;
import com.terios.logic.Task;
import com.terios.logic.ui.adapter.WeiboAdapter;
import com.terios.util.Exit;
/**
 * HomeActivity.java 2012-9-30 下午4:45:38
 * 
 * @author Wang Tengrui
 */
public class HomeActivity extends Activity implements IWeiboActivity,UpdateHandle{
	public static final int REFRESH_WEIBO = 1;
	public int nowPage = 1;// 当前第几页
	public int pageSize = CommonStrs.MAX_INFO_NUM;// 每页条数
	private ListView weiboList;// 微博信息显示
	private View login_progressBar;// 开始页菊花
	private LinearLayout moreWeibo;// 底部更多项
	private ProgressBar bottom_progressBar;// 底部更多项的菊花
	private ProgressBar title_progressBar;// 顶部title菊花
	private WeiboAdapter homeAdapter;// 微博信息的适配器
	PullToRefresh pullToRefresh;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);
		initview();// 初始化布局
		MainService.allActivity.add(this);
		init();// 开始请求数据
	}

	/**
	 * 初始化布局
	 */
	private void initview() {
		pullToRefresh = (PullToRefresh)this.findViewById(R.id.weibolist_pullDownView);
		pullToRefresh.setUpdateHandle(this);
		
		
		weiboList = (ListView) this.findViewById(R.id.weibolist);
		View bottom = LayoutInflater.from(this).inflate(R.layout.itembottom, null);
		View title = this.findViewById(R.id.home_title);// 标题头的布局
		title_progressBar = (ProgressBar) title.findViewById(R.id.title_progressBar);//顶部title菊花
		TextView tvname = (TextView) title.findViewById(R.id.tvinfo);//顶部title显示用户名的TextView
		tvname.setText(MainService.nowUser.getScreenName());// 设置顶部title当前登录用户screen_name
		ImageView btwriteWeibo = (ImageView) title.findViewById(R.id.title_bt_left);// 写微博按钮
		btwriteWeibo.setImageResource(R.drawable.ic_btn_post_text);
		bottom_progressBar = (ProgressBar) bottom.findViewById(R.id.progressBar);// 底部菊花
		weiboList.addFooterView(bottom);// 将菊花添加到ListView底部
		moreWeibo = (LinearLayout) bottom.findViewById(R.id.moreweibo);
		login_progressBar = this.findViewById(R.id.login_progresBar);
		
		// 点击底部更多的布局
		moreWeibo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				++nowPage;// 请求页数加一
				init();// 再次请求
				bottom_progressBar.setVisibility(View.VISIBLE);// 菊花滚动起来
			}
		});
		// 跳转到发送微博的页面
		btwriteWeibo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(HomeActivity.this, WriteWeibo.class);
				HomeActivity.this.startActivity(intent);
			}
		});
		
		// 当我们点击 某一条微博信息的时候就可以跳转到信息页面
		weiboList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Status nowstu = (Status) parent.getAdapter().getItem(position);// 从适配器中获取当前点击项的内容
				Intent intent = new Intent(HomeActivity.this, WeiboInfo.class); // 发送到WeiboInfo
				intent.putExtra("status",nowstu);
				HomeActivity.this.startActivity(intent);
			}
		});
	}
	
	@Override
	public void init() {
		// 任务参数（当前页面的分页信息）
		HashMap<String, Integer> paramHashMap = new HashMap<String, Integer>();
		paramHashMap.put("nowPage", Integer.valueOf(nowPage));
		paramHashMap.put("pageSize", Integer.valueOf(pageSize));

		// 加载主页微博信息任务
		Task task = new Task(CommonStrs.TASK_GET_USER_HOMETIMEINLINE, paramHashMap);
		MainService.allTask.add(task);
		title_progressBar.setVisibility(View.VISIBLE);//顶部菊花滚动起来
	}

	/**
	 * 刷新主页面信息
	 */
	public void refresh() {
		nowPage = 1;// 将当前页重置为第一页
		init();// 这里就是再次请求第一页信息
	}

	

	@SuppressWarnings("unchecked")
	@Override
	public void refresh(Object... param) {

		int flag = ((Integer) param[0]).intValue();// 获取任务标志
		switch (flag) {
		case REFRESH_WEIBO:
			title_progressBar.setVisibility(View.GONE);// 顶部title菊花关闭
			if (nowPage == 1) {
				login_progressBar.setVisibility(View.GONE);// ListView上层的菊花关闭
				List<Status> nowStatus = (List<Status>) param[1];
				homeAdapter = new WeiboAdapter(this, nowStatus);
				weiboList.setAdapter(homeAdapter);
			} else {
				bottom_progressBar.setVisibility(View.GONE);
				homeAdapter.addmoreDate((List<Status>) param[1]);
			}
			break;
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Exit.btexit(HomeActivity.this);// 按下返回键时要执行的动作
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	@Override
	public void onUpdate() {
		new PullRefreshThread(handler).start();
	}
	class PullRefreshThread extends Thread{
		private Handler handler;
		public PullRefreshThread(Handler handler){
			this.handler = handler;
		}
		@Override
		public void run(){
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			Message msg = handler.obtainMessage();
			handler.sendMessage(msg);
			super.run();
		}
	}
	private final Handler handler = new Handler(Looper.getMainLooper()){
		public void handleMessage(Message msg) { // 处理Message，更新ListView
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日   HH:mm:ss     ");
			refresh();
			Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
			String str = formatter.format(curDate);
			pullToRefresh.endUpdate(str);
		}
	};
}
